local cjson = require "cjson"
local upload = require "resty.upload"
local guid = require "common.guid"

return function ()
  local storagepath = "D:/tmp/upload/"
  local form = upload:new(4096)
  local file, ret

  while true do

    local typ, res, err = form:read()
    
    if not typ then
      break
    end
    
    if typ == "header" then

      if res[1] == "Content-Disposition" then
        local forminfo = ngx.re.match(res[2], '.+name="(.+)".+filename="(.+)".*')
        if forminfo and forminfo[2] then
          local savedname = guid()
          local savedpath = storagepath..savedname
          file = io.open(savedpath, "w+b")
          if file then
            ret = {}
            ret["filename"] = forminfo[2]
            ret["realname"] = savedname
          end
        end

      elseif res[1] == "Content-Type" then
        ret["isimage"] = not (not ngx.re.match(res[2], '^image/(jpeg)?(png)?(gif)?(bmp)?$'))
      end

    elseif typ == "body" then
      if file then
        file:write(res)
      end

    elseif typ == "part_end" then
      if file then
        ret["size"] = file:seek("end")
        file:close()
        file = nil
      end

    elseif typ == "eof" then
      break
    end
  end

  if ret then
    ngx.say(cjson.encode(ret))
  end
end
